/**
 * @ author: 汪孟苹
 */
define(["jquery","bbcare","fu/app/comm/comm",
    "scprit/followup/app/datatable/datatable.servers.js",
    "scprit/followup/app/datatable/datatable.ui.js","scprit/followup/app/courseReservation/courseList.ui.js"],function($,$bb,$comm,$datatableServers,$datatableUi,$courseListUi){
    var servers = {};
    var URL = $bb.baseUrl("followup");
    /**
     * 入参
     */
    var inParams = function(args){
    	var courseDate =  $(".fourDayItem.active").text();
        var data = JSON.stringify({
            data: {
                "args": JSON.stringify(args),
                "flag": 1,
                "courseDate":courseDate,
                "lecturerName": $.trim($('#lecturerName').val()),
                "courseName": $.trim($('#courseName').val()),
                "startDate":  $.trim($('#startDate').val()),
                "endDate":  $.trim($('#endDate').val()),
            }
        });
        return data;
    }
    /**
     * 出参
     */
    var outParams = function(data){
    	data.rows.map(function(a){
    		//状态：预约状态,1:预约,2:取消,3:完成
    		var arg = {1:"已预约",2:"已取消",3:"已完成"};
    		a.bespeakState = arg[a.bespeakState];
    	})
        return data.rows;
    }
    /**
     * columns
     */
    var columnsHisNo = function(e){
        return e.hisNo?e.hisNo:e.hisNo1 ? e.hisNo1 : e.hisNo2 ? e.hisNo2 : e.hisNo3 ? e.hisNo3 : "-";
    }
    var columnsPatientName = function(e){
        var imgSrc = 'page/followup/imgs/comm/';
        imgSrc += e.gender == 'F' ? 'girl.png' : 'boy.png';
        var h = '<img class="pic-sex" src='+imgSrc+'>';
            h += '<span class="patient-name">' + e.userName + '</span>'; 
        return h;
    }
    var columnsData = function(){
        var columnsArr = ["taskNumber","courseId","persenName",'phoneNo','courseName','joinNumber',"courseDate","bespeakState",null];
        return $datatableServers.getColumnsData(columnsArr);
    }
    /**
     * 行绘制回调函数
     */
    var rowCallback = function(row, data, index) {
    	var vhtml = data.bespeakState=="已完成"?"":'<div class="btn-cancel btn-look">取消</div><div class="btn-update btn-look">修改</div>';
    	
        var h = data.bespeakState=="已取消"?"":vhtml + '<div class="btn-signe btn-look">'+(data.bespeakState=="已完成"?"已签到":"签到")+'</div>';
        $('td:last()', row).html(h).css("width","120px");
        $("td:last() .btn-cancel",row).unbind("click");
        $("td:last() .btn-cancel",row).click(function(){
        	var args = {
    			"id": data.id,
    		    "userId": data.userId,
    		    "bespeakState": 2 //2取消预约，3签到
        	}
        	servers.cancelBespeak(args,function(){
        		 servers.resetBtn();
        	});
        });  
        $("td:last() .btn-update",row).click(function(){
        	servers.updateBespeak(data);
        });  
        $("td:last() .btn-signe",row).click(function(){
        	var args = {
    			"id": data.id,
    		    "userId": data.userId,
    		    "bespeakState": 3 //2取消预约，3签到
        	}
        	servers.cancelBespeak(args,servers.resetBtn);
        });  
    };
    /**
     * 初始化完成之后的回调函数
     */
    var initComplete = function(setting,json){
        $("#courseList").prev("div.row").children().first().removeClass("col-xs-6").addClass("col-xs-12");
        $("#courseList").prev("div.row").remove();
        $("#serchBtn").click(function(){
            $datatableUi.table.api().ajax.reload();  // 出发dt的重新加载数据的方法
            var args = $datatableUi.table.api().ajax.params();   //获取dt请求参数 
        });
        $("#resetBtn").click(function(){
        	 $(".fourDayItem").removeClass("active");
        	 servers.resetBtn();
        });
        $("#exportBtn").bind("click",function(){
        	var data = {
                 "lecturerName": $.trim($('#lecturerName').val()),
                 "course_name": $.trim($('#courseName').val()),
    			 "startDate":  $.trim($('#startDate').val()),
    			 "endDate":  $.trim($('#endDate').val()),
        	}
        	servers.exportCourseBespeak(data,function(file){});
        })
    }
    servers.resetBtn = function(){
    	 $("#courseName,#lecturerName,#startDate,#endDate").val("");
         $datatableUi.table.api().ajax.reload();  // 出发dt的重新加载数据的方法
         var args = $datatableUi.table.api().ajax.params();   //获取dt请求参数
    }
    /**
     * 获取datatable里的options
     */
    servers.getOptions = function(){
        var sessionId = $bb.getSessionStorage("sessionId");
        var options = {
            "ajax": {
                "url": URL + "followup/service/course/listCourseBespeakForPage?sessionId=" + sessionId,
                "data": inParams,
                "dataSrc": outParams
            },
            "columns": columnsData(),
            "rowCallback": rowCallback,
            "initComplete": initComplete,
        };
        return options;
    }
    /*
     * 课程预约-修改预约：
     * */
     servers.updateBespeak = function(data){
    	 var className = "updateBespeak";
         $comm.modal({
             "className": className,
             "tit": "修改预约信息",
         },function(){
        	 console.info(data)
         	 $courseListUi.updateBespeak({ 
                  "list": data,
                  "dom": $("." + className + " .modal-body"),
              });
              $("." + className).modal('show');
              $("#updateBespeak").unbind("click").bind("click",function(){
	           	   var phoneNo = $("#phoneNo").val(),persenName = $("#persenName").val(),joinNumber = $("#joinNumber").val();
	           	   if(phoneNo.length != 11){
	           		   $bb.toastShow("请输入正确的手机号")
	           	   }else if(persenName == ""){
	           		   $bb.toastShow("请输入听课人");
	           	   }else if(joinNumber == ""){
	           		   $bb.toastShow("请输入参加人数");
	           	   }else{
	           		   var arg = {
	           				"courseId": data.courseId,
	       				    "userId": data.userId,
	       				    "joinNumber": joinNumber,
	       				    "persenName": persenName,
	       				    "phoneNo": phoneNo,
	       				    "id":  data.id //预约id，为空：新增预约记录，不为空：修改预约记录
	           		   }
	           		   servers.doCourseToBespeak(arg,function(){
	           			   $bb.toastShow("预约成功");
	           			   $("." + className).modal('hide');
	           		   })
	           	   }
              })
         });
     };
     /*
      * 课程预约-添加预约：
      * */
      servers.addBespeak = function(params,callback){
     	 var className = "addBespeak";
          $comm.modal({
              "className": className,
              "tit": "添加预约",
          },function(){
          		$courseListUi.addBespeak({ 
                   "list": [{id:1,reasonName:"3"}],
                   "dom": $("." + className + " .modal-body"),
               });
               $("." + className).modal('show');
               $("#phoneNo").bind("keyup",function(){
            	   var arg = {
            		   "phoneNo": $(this).val(),
            		   "userName": ""
            	   }
            	   servers.selectPatientByParamForCourse(arg,function(data){
            		   $("#userList").empty();
            		   if(data.list.length){
            			   $.each(data.list,function(index,value){
            				   $("#userList").append("<option value='"+value.id+"'>"+value.user_name+"</option>")
            			   })
            			   var arg = {
            				   "userId": data.list[0].id,
            			   }
            			   servers.getCourseBespeakIndex(arg,function(data){
            				   $("#cList").empty();
            				   $.each(data.fourDayList,function(index,value){
            					   $("#cList").append("<option value='"+value.id+"'>"+value.courseName+"</option>")
            				   })
            			   })
            		   }else{
            			   $("#cList").empty();
            		   }
            	   })
               })
                $("#userList").change(function(){
                	var arg = {
                			"userId": $(this).val(),
                	}
                	servers.getCourseBespeakIndex(arg,function(data){
                		$("#cList").empty();
               		    $.each(data.fourDayList,function(index,value){
               			   $("#cList").append("<option value='"+value.id+"'>"+value.courseName+"</option>")
               		    })
                	})
                })
               $("#addBespeak").unbind("click").bind("click",function(){
            	   var phoneNo = $("#phoneNo").val(),courseId=$("#cList").val(),userId =$("#userList").val(),persenName = $("#persenName").val(),joinNumber = $("#joinNumber").val();
            	   if(phoneNo.length != 11){
            		   $bb.toastShow("请输入正确的手机号")
            	   }else if(!userId){
            		   $bb.toastShow("无效的手机号，请更换后重试")
            	   }else if(!courseId){
            		   $bb.toastShow("没有可预约的课程")
            	   }else if(persenName == ""){
            		   $bb.toastShow("请输入听课人");
            	   }else if(joinNumber == ""){
            		   $bb.toastShow("请输入参加人数");
            	   }else{
            		   var arg = {
            				"courseId": courseId,
        				    "userId": userId,
        				    "joinNumber": joinNumber,
        				    "persenName": persenName,
        				    "phoneNo": phoneNo,
        				    "id": "" 
            		   }
            		   servers.doCourseToBespeak(arg,function(){
            			   $("." + className).modal('hide');
            			   $bb.toastClose();
            			   servers.resetBtn
            		   })
            	   }
               })
          });
      };
      /*
       * 课程预约-取消预约（签到）：
       * */
       servers.cancelBespeak = function(params,callback){
           $bb.ajax({
               url: URL + "followup/webapi/service/course/cancelBespeak",
               data: JSON.stringify({
                   data: params
               }),
               success: function (data) {
                   if(data.success){
                       callback(data);
                   }
               }
           });
       };
      /*
       * 课程预约-课程预约（添加/修改）：
       * */
       servers.doCourseToBespeak = function(params,callback){
           $bb.ajax({
               url: URL + "followup/webapi/service/course/doCourseToBespeak",
               data: JSON.stringify({
                   data: params
               }),
               success: function (data) {
                   if(data.success){
                       callback(data.data);
                   }else{
                	  $bb.toastShow(data.msg ? data.msg : "请求预约数据出错！");
                   }
               }
           });
       };
      /*
       * 课程预约-查询有课程：
       * */
       servers.getCourseBespeakIndex = function(params,callback){
           $bb.ajax({
               url: URL + "followup/service/course/getCourseForFourDayOfAllByUser",
               data: JSON.stringify({
                   data: params
               }),
               success: function (data) {
                   if(data.success){
                       callback(data.data);
                   }else{
                	   $bb.toastShow(data.msg ? data.msg : "请求统计数据出错！");
                   }
               }
           });
       };
     /*
      * 课程预约-查询有课程的近四天的日期：
      * */
      servers.getCourseDayOfFour = function(params,callback){
          $bb.ajax({
              url: URL + "followup/webapi/service/course/getCourseDayOfFour",
              data: JSON.stringify({
                  data: params
              }),
              success: function (data) {
                  if(data.success){
                      callback(data.data);
                  }else{
                	  $bb.toastShow(data.msg ? data.msg : "请求统计数据出错！");
                  }
              }
          });
      };
      /*
       * 课程预约-通过名字或电话模糊查询患者：
       * */
       servers.selectPatientByParamForCourse = function(params,callback){
           $bb.ajax({
               url: URL + "followup/service/course/selectPatientByParamForCourse",
               data: JSON.stringify({
                   data: params
               }),
               success: function (data) {
                   if(data.success){
                       callback(data.data);
                   }else{
                 	  $bb.toastShow(data.msg ? data.msg : "请求统计数据出错！");
                   }
               }
           });
       };
      
    /*
     * 预约数据导出接口：
     * */
    servers.exportCourseBespeak = function(params,callback){
        var sessionId = $bb.getSessionStorage("sessionId");
        window.location.href = URL + "followup/service/course/exportCourseBespeak?sessionId=" + sessionId+urlEncode(params);
    };
 // urlEncode
    var urlEncode = function(param, key, encode) {
        if (param==null) return '';
        var paramStr = '';
        var t = typeof (param);
        if (t == 'string' || t == 'number' || t == 'boolean') {
            paramStr += '&' + key + '='  + ((encode==null||encode) ? encodeURIComponent(param) : param); 
        } else {
            for (var i in param) {
                var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i)
                paramStr += urlEncode(param[i], k, encode)
            }
        }
        return paramStr;

    }
    return servers;
});